<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreCasesRequest;
use App\Http\Requests\UpdateCasesRequest;
use App\Http\Resources\ServiceResource;
use App\Models\Cases;
use Illuminate\Http\Request;

class CasesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $title = $request->title ?? '';
        $per_page = $request->per_page ?? 10;
        $sort = json_decode($request->sort, true);

        $resources = Cases::when($title, function ($query) use ($title) {
            $query->where('title', 'like', '%' . $title . '%');
        })->when($sort, function ($query) use ($sort) {
            foreach ($sort as $item) {
                $val = str_replace('end', '', $item['order']);
                $query->orderBy($item['field'], $val);
            }
        }, function ($query) {
            return $query->orderBy('id', 'desc');
        })->paginate($per_page);
        return new ServiceResource($resources);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreCasesRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreCasesRequest $request)
    {
        return $this->successful(Cases::create($request->all()));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Cases  $case
     * @return \Illuminate\Http\Response
     */
    public function show(Cases $case)
    {
        return $this->successful($case);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Cases  $case
     * @return \Illuminate\Http\Response
     */
    public function edit(Cases $case)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateCasesRequest  $request
     * @param  \App\Models\Cases  $case
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateCasesRequest $request, Cases $case)
    {
        return $this->successful($case->update($request->all()));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Cases  $case
     * @return \Illuminate\Http\Response
     */
    public function destroy(Cases $case)
    {
        $case->delete();
        return $this->successful();
    }

    public function deleteMany(Request $request)
    {
        $ids = $request->ids;
        if (empty($ids)) {
            return $this->failed('请选择要删除的记录');
        }
        Cases::destroy($ids);
        return $this->successful();
    }
}
